package xyz.doikki.dkplayer.widget.component;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Build;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import xyz.doikki.dkplayer.R;
import xyz.doikki.videoplayer.controller.IControlComponent;
import xyz.doikki.videoplayer.controller.ControlWrapper;
import xyz.doikki.videoplayer.player.VideoView;
import xyz.doikki.videoplayer.util.L;
import xyz.doikki.videoplayer.util.PlayerUtils;

import static xyz.doikki.videoplayer.util.PlayerUtils.stringForTime;

public class TikTokView extends FrameLayout implements IControlComponent, SeekBar.OnSeekBarChangeListener {

    private final ImageView thumb;
    private final ImageView mPlayBtn;

    private final LinearLayout mBottomContainer;
    private final SeekBar mVideoProgress;
    private final ProgressBar mBottomProgress;

    private ControlWrapper mControlWrapper;



    private final ImageView mIcon;
    private final ProgressBar mProgressPercent;
    private final TextView mTextPercent;

    private final LinearLayout mCenterContainer;



    private final int mScaledTouchSlop;
    private int mStartX, mStartY;

    public TikTokView(@NonNull Context context) {
        super(context);
    }

    public TikTokView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TikTokView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    {
        LayoutInflater.from(getContext()).inflate(R.layout.layout_tiktok_controller, this, true);
        thumb = findViewById(R.id.iv_thumb);
        mPlayBtn = findViewById(R.id.play_btn);

        mBottomContainer = findViewById(R.id.bottom_container);
        mVideoProgress = findViewById(R.id.seekBar);
        mVideoProgress.setOnSeekBarChangeListener(this);
        mBottomProgress = findViewById(R.id.bottom_progress);


        mIcon = findViewById(R.id.iv_icon);
        mProgressPercent = findViewById(R.id.pro_percent);
        mTextPercent = findViewById(R.id.tv_percent);
        mCenterContainer = findViewById(R.id.center_container);

        mProgressPercent.setEnabled(false);

        //5.1以下系统SeekBar高度需要设置成WRAP_CONTENT
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
            mVideoProgress.getLayoutParams().height = ViewGroup.LayoutParams.WRAP_CONTENT;
        }


        setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mControlWrapper.togglePlay();
            }
        });
        mScaledTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
    }

    boolean move=false;

    /**
     * 解决点击和VerticalViewPager滑动冲突问题
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        int endX;
        int endY;

        switch (action) {
            case MotionEvent.ACTION_DOWN:
                mStartX = (int) event.getX();
                mStartY = (int) event.getY();



                return true;
            case MotionEvent.ACTION_MOVE:
                endX = (int) event.getX();
                endY = (int) event.getY();

                move=true;
                mCenterContainer.setVisibility(VISIBLE);


                //获取屏幕宽度
                int screenWidth = PlayerUtils.getScreenWidth(getContext(), false);

                int xDiss=Math.abs(endX - mStartX);
                int yDiss=Math.abs(endY - mStartY);
                if(xDiss>yDiss){

                    //停止进度
                    mControlWrapper.stopProgress();
                    mControlWrapper.stopFadeOut();


                    Log.d("TAG_xdistance", "onTouchEvent: "+xDiss);
                    Log.d("TAG_xdistance", "onTouchEvent: "+screenWidth);

                    double progressScale=((xDiss*1.0)/screenWidth);
                    double formattedProgress = Math.round(progressScale * 100.0) / 100.0;
                    Log.d("TAG_xdistance", "onTouchEvent: 滑动比"+formattedProgress);


                    double huadProgress = formattedProgress * mVideoProgress.getMax();
                    if((endX - mStartX)>0){
                        Log.d("TAG_xdistance", "onTouchEvent: 手指滑动方向：向右");
                        //huadProgress=+huadProgress;


                        mIcon.setImageResource(R.drawable.dkplayer_ic_action_fast_forward);
                    }else{
                        Log.d("TAG_xdistance", "onTouchEvent: 手指滑动进度：向左");
                        huadProgress=-huadProgress;

                        mIcon.setImageResource(R.drawable.dkplayer_ic_action_fast_rewind);

                    }


                    Log.d("TAG_xdistance", "onTouchEvent: 手指滑动进度"+huadProgress);
                    double progress = mVideoProgress.getProgress();
                    Log.d("TAG_xdistance", "onTouchEvent: seekbar当前进度"+progress);
                    double maxprogress = mVideoProgress.getMax();
                    Log.d("TAG_xdistance", "onTouchEvent: seekbar总进度"+maxprogress);





                    double totalProgress=progress+huadProgress;
                    if(totalProgress<0){
                        totalProgress=0;
                    }
                    if(totalProgress>maxprogress){
                        totalProgress=maxprogress;
                    }
                    Log.d("TAG_xdistance", "onTouchEvent: 原有进度+手指滑动进度："+totalProgress);
                    //设置进度
//                    mControlWrapper.seekTo((int) totalProgress);
                    //mVideoProgress.setProgress((int)(totalProgress));

                    mProgressPercent.setProgress((int)(totalProgress));
                    int processYY=(int) Math.round(progressScale * 100);
                    if(processYY>100){
                        processYY=100;
                    }
                    if (processYY<0){
                        processYY=0;
                    }
                    mTextPercent.setText(processYY+"%");

                    long duration = mControlWrapper.getDuration();
                    long newPosition = (duration * (int)totalProgress) / mVideoProgress.getMax();
                    Log.d("TAGStartStrag", "onStartTrackingTouch: 结束拖动 newPosition:"+newPosition);
                    Log.d("TAGStartStrag", "onStartTrackingTouch: 结束拖动 duration:"+duration);
                    mControlWrapper.seekTo((int) newPosition);



                }



                break;
            case MotionEvent.ACTION_UP:
                if(move){
                    mControlWrapper.startProgress();
                    mControlWrapper.startFadeOut();
                    move=false;
                    mCenterContainer.setVisibility(GONE);

                }



                endX = (int) event.getX();
                endY = (int) event.getY();
                if (Math.abs(endX - mStartX) < mScaledTouchSlop
                        && Math.abs(endY - mStartY) < mScaledTouchSlop) {
                    performClick();
                }
                break;
        }
        return false;
    }

    @Override
    public void attach(@NonNull ControlWrapper controlWrapper) {
        mControlWrapper = controlWrapper;
    }

    @Override
    public View getView() {
        return this;
    }

    private boolean mIsShowBottomProgress = false;
    /**
     * 是否显示底部进度条，默认显示
     */
    public void showBottomProgress(boolean isShow) {
        mIsShowBottomProgress = isShow;
    }
    @Override
    public void onVisibilityChanged(boolean isVisible, Animation anim) {

        if (isVisible) {
            mBottomContainer.setVisibility(VISIBLE);
            if (anim != null) {
                mBottomContainer.startAnimation(anim);
            }
            if (mIsShowBottomProgress) {
                mBottomProgress.setVisibility(GONE);
            }
        } else {
            mBottomContainer.setVisibility(GONE);
            if (anim != null) {
                mBottomContainer.startAnimation(anim);
            }
            if (mIsShowBottomProgress) {
                mBottomProgress.setVisibility(VISIBLE);
                AlphaAnimation animation = new AlphaAnimation(0f, 1f);
                animation.setDuration(300);
                mBottomProgress.startAnimation(animation);
            }
        }

    }

    @Override
    public void onPlayStateChanged(int playState) {
        switch (playState) {
            case VideoView.STATE_IDLE:
            case VideoView.STATE_PLAYBACK_COMPLETED:
                L.e("STATE_IDLE " + hashCode());
                thumb.setVisibility(VISIBLE);

                mBottomContainer.setVisibility(GONE);
                mBottomProgress.setProgress(0);
                mBottomProgress.setSecondaryProgress(0);
                mVideoProgress.setProgress(0);
                mVideoProgress.setSecondaryProgress(0);

                break;
            case VideoView.STATE_PLAYING:
                L.e("STATE_PLAYING " + hashCode());
                thumb.setVisibility(GONE);
                mPlayBtn.setVisibility(GONE);

                if (mIsShowBottomProgress) {
                    if (mControlWrapper.isShowing()) {
                        mBottomProgress.setVisibility(GONE);
                        mBottomContainer.setVisibility(VISIBLE);
                    } else {
                        mBottomContainer.setVisibility(GONE);
                        mBottomProgress.setVisibility(VISIBLE);
                    }
                } else {
                    mBottomContainer.setVisibility(GONE);
                }
                mBottomContainer.setVisibility(VISIBLE);
                //开始刷新进度
                mControlWrapper.startProgress();

                break;
            case VideoView.STATE_PAUSED:
                L.e("STATE_PAUSED " + hashCode());
                thumb.setVisibility(GONE);
                mPlayBtn.setVisibility(VISIBLE);
                break;
            case VideoView.STATE_START_ABORT:
                mBottomContainer.setVisibility(GONE);
                break;
            case VideoView.STATE_PREPARING:
                mBottomContainer.setVisibility(GONE);
                break;
            case VideoView.STATE_PREPARED:
                mBottomContainer.setVisibility(GONE);
                break;
            case VideoView.STATE_ERROR:
                mBottomContainer.setVisibility(GONE);
                L.e("STATE_ERROR " + hashCode());
                Toast.makeText(getContext(), R.string.dkplayer_error_message, Toast.LENGTH_SHORT).show();
                break;
            case VideoView.STATE_BUFFERING:
                //mPlayBtn.setSelected(mControlWrapper.isPlaying());
                // 停止刷新进度
                mControlWrapper.stopProgress();
                break;
            case VideoView.STATE_BUFFERED:
                //mPlayBtn.setSelected(mControlWrapper.isPlaying());
                //开始刷新进度
                mControlWrapper.startProgress();
                break;
        }
    }

    @Override
    public void onPlayerStateChanged(int playerState) {

        Activity activity = PlayerUtils.scanForActivity(getContext());
        if (activity != null && mControlWrapper.hasCutout()) {
            int orientation = activity.getRequestedOrientation();
            int cutoutHeight = mControlWrapper.getCutoutHeight();
            if (orientation == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {
                mBottomContainer.setPadding(0, 0, 0, 0);
                mBottomProgress.setPadding(0, 0, 0, 0);
            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
                mBottomContainer.setPadding(cutoutHeight, 0, 0, 0);
                mBottomProgress.setPadding(cutoutHeight, 0, 0, 0);
            } else if (orientation == ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE) {
                mBottomContainer.setPadding(0, 0, cutoutHeight, 0);
                mBottomProgress.setPadding(0, 0, cutoutHeight, 0);
            }
        }

    }
    private boolean mIsDragging;
    @Override
    public void setProgress(int duration, int position) {

        if (mIsDragging) {
            return;
        }
        if (mVideoProgress != null) {
            if (duration > 0) {
                mVideoProgress.setEnabled(true);
                int pos = (int) (position * 1.0 / duration * mVideoProgress.getMax());
                mVideoProgress.setProgress(pos);
                mBottomProgress.setProgress(pos);

                Log.d("TAGStartStrag", "setProgress: pos:"+pos);
                Log.d("TAGStartStrag", "setProgress: position:"+position);
                Log.d("TAGStartStrag", "setProgress: duration:"+duration);

            } else {
                mVideoProgress.setEnabled(false);
            }
            int percent = mControlWrapper.getBufferedPercentage();
            if (percent >= 95) { //解决缓冲进度不能100%问题
                mVideoProgress.setSecondaryProgress(mVideoProgress.getMax());
                mBottomProgress.setSecondaryProgress(mBottomProgress.getMax());
            } else {
                mVideoProgress.setSecondaryProgress(percent * 10);
                mBottomProgress.setSecondaryProgress(percent * 10);
            }
        }

    }




    @Override
    public void onLockStateChanged(boolean isLocked) {
        onVisibilityChanged(!isLocked, null);
    }

    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
        if (!fromUser) {
            return;
        }

        long duration = mControlWrapper.getDuration();
        long newPosition = (duration * progress) / mVideoProgress.getMax();
//        if (mCurrTime != null)
//            mCurrTime.setText(stringForTime((int) newPosition));
    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {
        mIsDragging = true;
        Log.d("TAGStartStrag", "onStartTrackingTouch: 开始拖动");
        mControlWrapper.stopProgress();
        mControlWrapper.stopFadeOut();

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {

        long duration = mControlWrapper.getDuration();
        long newPosition = (duration * seekBar.getProgress()) / mVideoProgress.getMax();
        Log.d("TAGStartStrag", "onStartTrackingTouch: 结束拖动 newPosition:"+newPosition);
        Log.d("TAGStartStrag", "onStartTrackingTouch: 结束拖动 duration:"+duration);
        mControlWrapper.seekTo((int) newPosition);
        mIsDragging = false;
        mControlWrapper.startProgress();
        mControlWrapper.startFadeOut();
    }
}
